import request from "@/service/request";
import { baseUrl } from "@/config/env";
import qs from "qs";
import store from "@/store";

const methods = ["get", "post", "put", "delete", "request"];
export default class BaseService {
	constructor() {
		const crud = {
			page: "page",
			list: "list",
			info: "info",
			add: "add",
			delete: "delete",
			update: "update"
		};
		this.$baseUrl = baseUrl
		this.$store = store;
		if (!this.permission) {
			this.permission = {};
		}

		for (let i in crud) {
			if (this.namespace) {
				this.permission[i] = this.namespace.replace(/\//g, ":") + ":" + crud[i];
			} else {
				this.permission[i] = crud[i];
			}
		}
		this.initRquest();
	}

	initRquest() {
		let path = "";

		if (process.env.NODE_ENV == "development") {
			path = this.proxy || baseUrl;
		} else {
			if (this.proxy) {
				path = this.url;
			} else {
				path = baseUrl;
			}
		}

		if (this.namespace) {
			path += "/" + this.namespace;
		}

		for (const key of methods) {
			this["$" + key] = (url, ...args) => {
				if (url.indexOf("http") !== 0) {
					if (url[0] === "@") {
						url = url.replace("@", "");
					} else {
						url = path + url;
					}
				}

				if (key == "post") {
					// args[0] = qs.stringify(args[0]);
				}
				if (key == "request") {
					return request(url, ...args);
				}
				return request[key](url, ...args);
			};
		}
	}
	request(options = {}) {
		if (!options.params) {
			options.params = {};
		}

		let path = "";

		if (process.env.NODE_ENV == "development") {
			path = this.proxy || baseUrl;
		} else {
			if (this.proxy) {
				path = this.url;
			} else {
				path = baseUrl;
			}
		}

		if (this.namespace) {
			path += "/" + this.namespace;
		}

		if (options.url.indexOf("http") !== 0) {
			if (options.url[0] === "@") {
				options.url = options.url.replace("@", "");
			} else {
				options.url = path + options.url;
			}
		}

		return request(options);
	}

	list(params) {
		return this.$post("/list", params);
	}
	pagination(params = {}, res = {}, args = {}) {
		return {
			list: res.data,
			pagination: {
				...params,
				page: params.page,
				size: params.size || params.pagesize,
				total: res.total
			},
			...args
		};
	}
	page(params) {
		return this.$post("/page", params).then(res => {
			return {
				list: res.data,
				pagination: {
					page: 1,
					size: 20,
					total: 5
				}
			};
		});
	}

	info(params) {
		return this.$get("/info", params);
	}

	update(params) {
		return this.$post("/update", params);
	}

	delete(params) {
		return this.$post("/delete", params);
	}

	add(params) {
		return this.$post("/add", params);
	}
}
